package v1

import (
	"ginblog/model"
	"ginblog/utils/errmsg"
	"ginblog/utils/validate"
	"github.com/gin-gonic/gin"
	"strconv"
)

var code int

// 查询用户是否存在
func CheckUser(c *gin.Context) {
	name := c.Query("name") // query数据
	code = model.CheckUser(name)
	Response(c, code, "")
}

// 添加用户
func AddUser(c *gin.Context) {
	data := &model.User{}
	var msg string
	c.ShouldBindJSON(data)
	msg, code = validate.Validate(data)
	if code != errmsg.SUCESS {
		Response(c, code, msg)
		return
	}
	code = model.CheckUser(data.Username)
	if code == errmsg.SUCESS {
		code = model.CreateUser(data)
	}

	// 临时忽略某个字段
	res := struct {
		*model.User
		Password bool `json:"password,omitempty"`
	}{
		User: data,
	}

	Response(c, code, res)
}

// 查询单个用户

// 查询用户列表
func GetUsers(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	if pageSize == 0 {
		pageSize = -1
	}
	if pageNum == 0 {
		pageNum = -1
	}
	users, code := model.GetUsers(pageSize, pageNum)
	Response(c, code, users)
}

// 编辑用户
func EditUser(c *gin.Context) {
	var data model.User
	id, _ := strconv.Atoi(c.Param("id"))
	c.ShouldBindJSON(&data)

	// 下面这句话可以放到钩子函数中，但是放在这里代码可读性更高
	code = model.CheckUser(data.Username)
	if code == errmsg.SUCESS {
		code = model.EditUser(id, &data)
	}
	Response(c, code, "")
}

// 删除用户
func DeleteUser(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code = model.DeleteUser(id)
	Response(c, code, "")
}
